<template>
  <div class="add-form">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span v-if="!isAdd">新增题目</span>
        <span v-if="isAdd">编辑题目</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="cancel">取消</el-button>
        <el-button style="float: right; padding: 3px 0" type="text" @click="submitForm">确定</el-button>
      </div>
      <el-form label-width="100px" :model="form" :rules="rules" ref="form">
        <div class="item-box">
          <el-form-item label="题目" prop="questionDesc" style="width: 50%">
            <el-input
              type="textarea"
              :rows="8"
              placeholder="请输入题目"
              v-model.trim="form.questionDesc"
              :maxlength="200"
            />
          </el-form-item>

          <el-form-item label="题目图片"  style="width: 50%">
            <el-upload
              class="avatar-uploader"
              accept=".jpg,.jpeg,.png"
              :action="fileUploadUrl"
              :show-file-list="false"
              :on-success="themeHandleSuccess"
              v-loading="themeLoading"
              :before-upload="beforeThemeUpload">
              <img v-if="themeUrl" :src="themeUrl" class="avatar" style="width: 330px;height: 210px;paddig-top: 10px;"/>
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </div>

        <div class="item-box">
          <el-form-item label="答案解析" prop="basis" style="width: 50%">
            <el-input
              type="textarea"
              :rows="8"
              placeholder="请输入题目"
              v-model.trim="form.basis"
              :maxlength="300"
            />
          </el-form-item>
        </div>


        <div class="item-box">
          <el-form-item label="题目标签" prop="keywords"  style="width: 50%">
            <el-input v-model="form.keywords" size="medium" maxlength="20" style="width: 400px;"/>
          </el-form-item>
          <el-form-item label="分值" prop="score" :inline="true"  style="width: 49%">
            <el-input-number size="medium" style="width: 400px;"
                             v-model="form.score"
                             controls-position="right"
                             :min="1"
                             :max="10"
            ></el-input-number>
          </el-form-item>
        </div>
        <div class="item-box">
          <el-form-item label="类型">
            <!-- <el-radio v-model="optionType" label="0">单选</el-radio>
            <el-radio v-model="optionType" label="1">多选</el-radio>
            <el-radio v-model="optionType" label="2">判断</el-radio> -->
            <el-select v-model="optionType" style="width: 400px;" class="filter-item" size="medium" clearable filterable
                       placeholder="题目类型">
              <el-option v-for="item in typeList" :key="item.id" :label="item.label" :value="item.id-0">
              </el-option>
            </el-select>
          </el-form-item>

        </div>
        <div class="item-box" v-for="(item, index) in form.lists" :key="index">
          <el-form-item :label="`选项${(index + 1)}`" style="width: 70%">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入选项内容"
              v-model.trim="item.answerDesc"
              :maxlength="100"/>
          </el-form-item>
          <el-radio v-model="form.rightNum" :label="index" v-if="optionType == 0 || optionType == 2">是否正确选项</el-radio>
          <el-checkbox v-model="item.isTrue" v-if="optionType == 1 || optionType == 3">是否正确选项</el-checkbox>
          <!--  <i class="el-icon-close" style="font-size: 32px" @click="delTest(index)"></i> -->
          <el-button type="danger" size="mini" icon="el-icon-delete" circle @click="delTest(index,item.id)"></el-button>
        </div>
        <!-- <el-form-item>
          <div class="test-add" @click="addTest()">
            <i class="el-icon-circle-plus-outline" style="margin-right: 5px;text-align: center;"></i>新增选项
          </div>
        </el-form-item> -->
        <el-row :gutter="20">
          <el-col :span="12" :offset="11">
            <div>
              <el-popover placement="top-start" width="110" trigger="hover" content="新增选项">
                <el-button slot="reference" size="mini" type="success" @click="addTest()"
                           icon="el-icon-plus" circle/>
              </el-popover>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script>
  import { delBankQuesOption, addQuestion } from '@/api/business/questionBank'
  import Treeselect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  import { tree } from '@/api/framework/system/specialty'
  //import { getImageUrl } from '@/utils/index'

  export default {
    components: { Treeselect },
    data() {
      return {
        fileUploadUrl: process.env.FILE_UPLOAD,
        themeLoading:false,
        themeUrl: null,
        optionType: 0,
        typeList: [{ 'id': 0, 'label': '单选题' }, { 'id': 1, 'label': '多选题' }, { 'id': 2, 'label': '判断题' }],
        form: {
          bankId: '',
          questionDesc: '',
          score: 1,
          keywords:'',
          basis:'',
          optionType: '0',
          questionImg: '',
          questionImgs: [],
          questionNum: 1,
          majorId: null,
          rightNum: 0,
          lists: [],
          isDelete: '0'
        },
        rules: {
          questionDesc: [{ required: true, message: '请输入题目' }],
          score: [{ required: true, message: '请输入分数' }],
          keywords: [{ required: true, message: '请填写题目标签' }],
        },
        test: {
          answerDesc: '',
          answerImg: '',
          answerImgs: [],
          isTrue: '0',
          isDelete: '0',
          orderNum: 0,
          bankId: '',
          id:'',
        },
        loading: false,
        submiting: false,
        specialty: []
      }
    },
    props: {
      index: {
        type: Number,
        default: 0
      },
      bankId: {
        type: String,
        default: ''
      },
      item: {
        type: Object,
        default: null
      },
      isAdd: {
        type: Boolean,
        required: true
      }
    },
    watch: {
      optionType(newVal, oldVal) {
        if (newVal == 0 || newVal == 2) {
          this.form.lists = this.form.lists.map(item => {
            item.isTrue = 0
            return item
          })
        } else {
          this.form.lists = this.form.lists.map(item => {
            item.isTrue = false
            return item
          })
        }
      }
    },
    created() {
      //this.getSpecialtyType()
    },
    mounted() {
      if (this.item) {
        let json = JSON.parse(JSON.stringify(this.item))
        this.optionType = this.item.optionType
        // if (json.questionImg) {
        //   json.questionImgs = [json.questionImg]
        // } else {
        //   json.questionImgs = []
        // }

        for (let i = 0; i < json.lists.length; i++) {
          if (json.lists[i].answerImg) {
            json.lists[i].answerImgs = [json.lists[i].answerImg]
          } else {
            json.lists[i].answerImgs = []
          }

          if (this.optionType == 0 || this.optionType == 2) {
            if (json.lists[i].isTrue == 1) {
              json.rightNum = i
            }
            json.lists[i].isTrue == 0
          } else {
            if (json.lists[i].isTrue == 1) {
              json.lists[i].isTrue = true
            } else {
              json.lists[i].isTrue = false
            }
          }
        }
        setTimeout(() => {
          this.form = JSON.parse(JSON.stringify(json))
          let newQuestion = []
          if (this.item.questionImg) {
            newQuestion.push({
              name: this.item.questionImg.name,
              url: this.item.questionImg.url
            })
          }
          if (typeof this.item.questionImg == 'string' && this.item.questionImg !== '') {
            var list = JSON.parse(this.item.questionImg)
            if(list!=null){
              this.themeUrl=list[0].url;
            }
          }
          //this.form.questionImgs = newQuestion
          let lists = this.form.lists
          lists &&
          lists.map(r => {
            if (r.answerImgs.length > 0) {
              let data = JSON.parse(r.answerImgs)
              let arr = []
              arr.push({
                name: data.name,
                url: data.url
              })
              if (r.answerImgs) r.answerImgs = arr
            }
          })
          this.form.lists = lists
        }, 100)
        this.test.bankId = this.item.bankId
      } else {
        this.form.bankId = this.bankId
        this.test.bankId = this.bankId
        this.form.lists.push(JSON.parse(JSON.stringify(this.test)))
      }
    },
    methods: {
      //getImageUrl,
      // addSelect(value) {
      //   this.form.majorId = value.value
      //   this.form.majorType = value.label
      // },
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children
        }
      },
      getSpecialtyType() {
        tree().then(data => {
          this.specialty = []
          const type = { id: '0', label: '题目专业分类', children: [] }
          type.children = data
          this.specialty.push(type)
        })
      },
      addTest() {
        if (this.optionType == 2) {
          if (this.form.lists.length == 2) {
            this.$message({
              message: '判断题最多允许两个选项，请删除多余选项',
              type: 'warning'
            })
            return
          }
        }
        this.test.orderNum = this.form.lists.length + 1
        let test = JSON.parse(JSON.stringify(this.test))
        this.form.lists.push(test)
      },
      delTest(index, id) {
        this.$alert('确定删除选项,删除后不可恢复？', '提示消息', {
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          this.form.lists.splice(index, 1)
          if (id != null && id != '' && id != undefined) {
            delBankQuesOption(id).then(res => {
              this.$notify({
                title: '删除成功',
                type: 'success',
                duration: 2500
              })
            })
          }
        })
      },
      cancel() {
        this.$parent.isEdit = true
        //this.$parent.isAdd = true
        this.$emit('cancelAdd')
      },
      submitForm() {
        this.$refs.form.validate(valid => {
          if (!valid) {
            this.submiting = false
            return
          }
          // if (this.form.majorId == null) {
          //   this.$message.error('请选择专业类别')
          //   return false
          // }
          if (this.form.questionDesc == '' && this.form.questionImgs.length == 0) {
            this.$message.error('请输入题目')
            return false
          }
          if (this.form.questionImgs && this.form.questionImgs.length > 0) {
            this.form.questionImg = this.form.questionImgs[0]
          }
          // else {
          //   this.form.questionImg = ''
          // }

          let isTrue = false
          for (let i = 0; i < this.form.lists.length; i++) {
            if (this.form.lists[i].answerDesc == '') {
              this.$message.error('请输入题目')
              return false
            }

            if (this.form.lists[i].answerImgs && this.form.lists[i].answerImgs.length > 0) {
              this.form.lists[i].answerImg = this.form.lists[i].answerImgs[0]
            } else {
              this.form.lists[i].answerImg = ''
            }

            if (this.optionType == 0 || this.optionType == 2) {
              if (this.form.rightNum == i) {
                this.form.lists[i].isTrue = 1
                isTrue = true
              } else {
                this.form.lists[i].isTrue = 0
              }
            } else {
              if (this.form.lists[i].isTrue) {
                isTrue = true
                this.form.lists[i].isTrue = 1
              } else {
                this.form.lists[i].isTrue = 0
              }
            }
          }
          this.form.optionType = this.optionType
          if (!isTrue) {
            this.$message.error('至少需要一个正确答案')
            return false
          }
          var list = []
          list.push(this.form)
          addQuestion({
            lists: list
          })
            .then(res => {
              this.$message.success('保存成功')
              this.$emit('setForm', this.form)
            })
            .catch(err => {
              this.$message.error(err.message)
            })
        })
      },
      beforeThemeUpload(file) {
        var imgfileType="'image/jpeg','image/jpg','image/pjpeg','image/x-png','image/png'";
        const isJPG =imgfileType.indexOf(file.type )>0;
        if (!isJPG) {
          this.$message.error('上传课程封面图片只能是 jpg、png、jpeg 格式!')
          return false;
        }
        this.themeLoading=true
      },
      themeHandleSuccess(response, file, fileList) {
        this.form.questionImg = []
        const uploadFile = {
          name: file.name,
          url: file.response
        }
        this.themeUrl = uploadFile.url
        this.form.questionImg.push(uploadFile)
        this.form.questionImg = JSON.stringify(this.form.questionImg)
        this.themeLoading=false
      },
    }
  }
</script>
<style lang="scss" scoped>
  .add-form {
    //background-color: #eeeeee;
    color: #aaa;
    padding: 5px;
  }

  .test-add {
    margin-top: 10px;
    height: 34px;
    cursor: pointer;
    border: dashed 1px #aaa;
    display: flex;
    align-items: center;
    padding-left: 10px;
    background-color: #eeeeee;
  }

  .item-box {
    display: flex;
    width: 100%;
    justify-content: space-between;
    align-items: center;
    margin-top: 5px;
  }

  .el-icon-close {
    cursor: pointer;
  }

  .treeselect-main {
    margin-top: 1px;
    width: 500px;
    line-height: 35px;

    .vue-treeselect__placeholder {
      line-height: 35px;
    }

    .vue-treeselect__control {
      height: 36px;
    }

  }
</style>
